from django.forms import *
from django.utils.translation import ugettext_lazy as _

from payment.forms import PaymentContactInfoForm
from payment.utils import pay_ship_save, get_processor_by_key

from satchmo_store.contact.models import Contact, PhoneNumber
from satchmo_store.shop.models import Order

REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'phone']

class QuickOrderForm(PaymentContactInfoForm):

    fax = CharField(label=_('Fax'), required=False)
    order_notes = CharField(label=_('Notes'), required=False, widget=Textarea)

    def __init__(self, *args, **kwargs):
        if 'data' in kwargs:
            kwargs['data']['copy_address'] = True # shipping fields are not required
        super(QuickOrderForm, self).__init__(*args, **kwargs)
        self.required_billing_data = []
        for field_name in self.fields:
            self.fields[field_name].required = field_name in REQUIRED_FIELDS
                

    def save(self, cart, contact):

        self.save_info(contact=contact)

        if self.cleaned_data['fax']:
            fax, created = PhoneNumber.objects.get_or_create(contact=contact, type='Fax')
            fax.phone = self.cleaned_data['fax']
            fax.save()

        order = Order(contact=contact, notes=self.cleaned_data['order_notes'])
        pay_ship_save(order, cart, contact, shipping="", discount="")
            
        processor = get_processor_by_key('PAYMENT_AUTOSUCCESS')
        processor.prepare_data(order)
        processor.process(order)
          
        cart.empty()

        return order
